package com.carb.task;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.carb.entity.Business;
import com.carb.enums.BusinessStatus;
import com.carb.service.IBusinessService;
import jakarta.annotation.Resource;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务：定时处理业务状态
 */
@Component
@Slf4j
public class BusinessTask implements ApplicationListener<ApplicationReadyEvent> {

    @Resource
    private IBusinessService businessService;

    /**
     * 项目启动后立即执行
     */
    @Override
    public void onApplicationEvent(@NonNull ApplicationReadyEvent event) {
        handleUnacceptedBusiness();
        handleInProgressBusiness();
    }

    /**
     * 定时处理未接单业务（每2小时）
     */
    @Scheduled(cron = "0 0 */2 * * ?")
    public void handleUnacceptedBusiness() {
        log.info("定时处理未接单业务：{}", LocalDateTime.now());
        // 1、查询未接单业务，且创建时间超过2小时
        LocalDateTime twoHoursAgo = LocalDateTime.now().minusHours(2);
        List<Business> unacceptedBusinessList = businessService.list(Wrappers.lambdaQuery(Business.class)
                .eq(Business::getStatus, BusinessStatus.UNACCEPTED)
                .lt(Business::getCreateTime, twoHoursAgo));

        // 2、更新业务为已退款
        if (!unacceptedBusinessList.isEmpty()) {
            for (Business unacceptedBusiness : unacceptedBusinessList) {
                businessService.refundBusiness(unacceptedBusiness.getId());
            }
        }
    }

    /**
     * 定时处理进行中业务（每日凌晨2点）
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void handleInProgressBusiness() {
        log.info("定时处理进行中业务：{}", LocalDateTime.now());
        // 1、查询进行中业务，且创建时间超过2小时
        LocalDateTime twoHoursAgo = LocalDateTime.now().minusHours(2);
        List<Business> inProgressBusinessList = businessService.list(Wrappers.lambdaQuery(Business.class)
                .eq(Business::getStatus, BusinessStatus.IN_PROGRESS)
                .lt(Business::getCreateTime, twoHoursAgo));

        // 2、更新业务为已完成
        if (!inProgressBusinessList.isEmpty()) {
            for (Business inProgressBusiness : inProgressBusinessList) {
                businessService.completeBusiness(inProgressBusiness.getId());
            }
        }
    }

}
